//
//  MainAccountVC.swift
//  d11
//
//  Created by peale on 2018/9/14.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import Eagleeyes.DevicePrint
class MainAccountVC: BXBaseVC,UITableViewDelegate,UITableViewDataSource {
    let  reuseIdentifierHeadID : NSString = "MainAccountHeaderView"
    let  reuseIdentifierID : NSString = "MainAccountCell"
    let  reuseIdentifierID2 : NSString = "MainAccountBtnCell"
    let  reuseIdentifierID3 : NSString = "MainAccountSelectCell"
     let  reuseIdentifierID4 : NSString = "MainAccountInputCell"
    let  reuseIdentifierID5 : NSString = "MainAccountSubmitBtnCell"
    
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 10, width: self.view.width, height:kScreenHeight-kTabBarBottom-10), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.white
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
//        if #available(iOS 11.0, *) {
//            table.contentInsetAdjustmentBehavior = .never
//
//        } else {
//            self.automaticallyAdjustsScrollViewInsets = false
//        }
        return table
    }()
    
    var arrayList : [[String:Any]]? //数据列表
    var inDict : [String:Any]? //转入平台字典
    var outDict : [String:Any]?  //转出平台字典
    var moneyStr : String?  //转账金额
    var requestCount :Int = 0
    var isNoLogin : Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "主账户"
        if self.arrayList == nil {
           self.arrayList = [[String:Any]]()
        }
        self.showLoadHUD(title: "")
        self.getPlatformList()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)

        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
    }
    
    //一键转入/回收
    func outOrIn2(index:Int,dict:[String:Any]){
        if arrayList != nil {
            self.requestCount = 0
            self.isNoLogin = false
            var typeName:String = "转入"
            if dict["id"] as? String ?? "" == "10000" {
                typeName = "回收"
            }
            var outList = [[String:Any]]()
              let ingpid = dict["id"] as? String
            for (_ , item1) in arrayList!.enumerated(){
                 let money = item1["val"] as? String ?? "0.00"
                if money != "0.00" &&  money != "维护中..." && money != "读取中..." && ingpid != item1["id"] as? String ?? "" {
                    outList.append(item1)
                }
            }
            self.showLoadHUD(title: "\(typeName)中..." as NSString)
            for (_ , item) in outList.enumerated(){
                if self.isNoLogin == true{
                    break
                }
                let gpid = item["id"] as? String
                let money = item["val"] as? String ?? "0.00"
                if gpid != nil && gpid != "" && ingpid != nil   && ingpid != ""{
                    NetWorkRequest(API.transaction(url: "0ef07eb", tout: gpid!, tin: ingpid!, amount: money), completion: { (responseData,statusCode,strData) -> (Void) in
                        let dataDict =  responseData["data"].dictionaryObject
                        let response = dataDict?["response"] as? [String:Any]
                        let code = response?["c"] as? Int ?? -1
                        // let data =  response?["data"] as? [String:Any] ?? [:]
                        DispatchQueue.main.async {
                            self.requestCount += 1
                            if code == 0{
                                if self.requestCount == outList.count{
                               //      self.requestEagleeyes()
                                     self.dismissLoadHUD()
                                   UIHelper.alertSimpleMessage(about: "\(typeName)成功!", withDescription: "", in: self)
                                    for(index,value) in (self.arrayList?.enumerated())!{
                                        let gpid = value["id"] as? String
                                        if gpid != nil && gpid != ""{
                                            var dict = value
                                            if value["status"] != nil{
                                                dict.removeValue(forKey: "status")
                                                dict["val"] = "读取中..."
                                                self.arrayList![index] = dict
                                                self.tableView.reloadData()
                                            }
                                            self.getGPSBalance(gpid: gpid!, row: index)
                                        }
                                    }
                                    self.tableView.reloadData()
                                }
                                
                            }else if code == 999 || code == 1150 {
                                DispatchQueue.main.async {
                                    self.isNoLogin = true
                                    self.dismissLoadHUD()
                                    LoginViewController.loginIfNeedController(currentController: self) {}
                                }
                            }else{
                                DispatchQueue.main.async {
                                    if self.requestCount == outList.count{
                                        self.dismissLoadHUD()
                                    }
                                    UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                                }
                            }
                        }
                        
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        DispatchQueue.main.async {
                            self.requestCount += 1
                            if reCode == "21002"{
                                self.isNoLogin = true
                                self.dismissLoadHUD()
                                LoginViewController.loginIfNeedController(currentController: self) {}
                            }else{
                                if self.requestCount == outList.count{
                                    self.dismissLoadHUD()
                                }
                                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                            }
                        }
                    }) { () -> (Void) in
                        DispatchQueue.main.async {
                            self.requestCount += 1
                            if self.requestCount == outList.count{
                                self.dismissLoadHUD()
                            }
                            UIHelper.alertSimpleMessage(about: "\(typeName)未成功，请稍后重试。", withDescription: "", in: self)
                        }
                    }
                    
                }
            }
        }
        
    }
    //获取平台列表数据
    func getPlatformList() -> Void {
        NetWorkRequest(API.getAvailableGPS(url: "ae1b1af"), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                let dataDict =  responseData["data"].dictionaryObject
                let response = dataDict?["response"] as? [String:Any]
                let code = response?["code"] as? Int ?? -1
                let dataArray =  response?["data"] as? [Any] ?? []
                let datalist =  dataArray[0] as? [[String:Any]] ?? []
                self.arrayList = datalist
                self.tableView.reloadData()
                //单个获取金额
                for(index,value) in (self.arrayList?.enumerated())!{
                    let gpid = value["id"] as? String
                    if gpid != nil && gpid != ""{
                        self.getGPSBalance(gpid: gpid!, row: index)
                    }
                }
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
    //获取某平台金额
    func getGPSBalance(gpid:String,row:Int){
        NetWorkRequest(API.getGPSBalance(url: "1fb978f", gpid: gpid,playername:UserDefaults.standard.value(forKey: DefaultKey.USER_LOGIN_NAME) as? String  ?? ""), completion: { (responseData,statusCode,strData) -> (Void) in
            let dataDict =  responseData["data"].dictionaryObject
            let response = dataDict?["response"] as? [String:Any]
            let code = response?["code"] as? Int ?? -1
            let data =  response?["data"] as? [String:Any] ?? [:]
            var dict  = self.arrayList![row]
            dict["val"] = "读取中..."
            dict.removeValue(forKey: "status")
            if code == 0{
                let tempGpid  = data["gpid"] as? String
                if tempGpid  != nil && tempGpid == dict["id"] as? String { //id相同
                    let val:String? = data["val"] as? String
                    if val == nil{
                        if data["val"] is Int {
                            print("整型\(data["val"])")
                            dict["val"] = String(format: "%.2f", Double(data["val"] as! Int))
                            dict["status"] = 1
                        }else if data["val"] is Double {
                            print("double\(data["val"])")
                            dict["val"] = String(format: "%.2f",data["val"] as! Double)
                            dict["status"] = 1
                        }else{
                            dict["val"] = "0.00"
                            dict["status"] = 1
                        }
                        
                    }else{
                        let value : Double =  Double(val!) ?? 0.0
                        dict["val"] = String(format: "%.2f",value)
                        dict["status"] = 1
                    }
                    print("\(dict)")
                    self.arrayList?[row] = dict
                }else{
                    print("错误1\(gpid)")
                    dict["val"] = "0.00"
                    dict["status"] = 1
                    self.arrayList?[row] = dict
                }
            }else if code == 1407{
               dict["val"] = "维护中..."
                dict["status"] = 0
               self.arrayList?[row] = dict
            }else{
                 print("错误2\(gpid)")
                dict["val"] = "0.00"
                dict["status"] = 1
                 self.arrayList?[row] = dict
            }
            
             self.tableView.reloadData()
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                 print("错误32\(gpid)")
                var dict  = self.arrayList![row]
                dict["val"] = "0.00"
                dict["status"] = 1
                self.arrayList?[row] = dict
                self.tableView.reloadData()
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                var dict  = self.arrayList![row]
                dict["val"] = "0.00"
                dict["status"] = 1
                self.arrayList?[row] = dict
                self.tableView.reloadData()
            }
        }
    }
    
    //调用鹰眼接口
    func requestEagleeyes(){
//        RequestHelper.get(atPath:"/home/getGeo", withCompletion: { (data) in
//            var dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
//            print("获取IP\(dataArray)")
//            if let ip = dataArray?["ip"] as? String {
//                DispatchQueue.main.async {
                    let blackbox :String = DevicePrint.getBlackBox() ?? ""
                    NetWorkRequest(API.requsetEagleeyes2(url: "94a0356", blackBox: blackbox, type: "transfer", dno: "",ipaddress:""), completion: { (responseData,statusCode,strData) -> (Void) in
                        print("转账后鹰眼返回:",responseData,statusCode,strData)
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        print("转账后鹰眼返回:",faildInfo,reCode,msg)
                    }) { () -> (Void) in
                        print("转账后鹰眼返回错误")
                    }
                }
//            }
//        }, withError: { error in
//        })
//    }//withdrawal deposit
    
    //调用一键回收/转入
//    func outOrIn(index:Int,dict:[String:Any]){
//        var typeName:String = "转帐"
//        if dict["id"] as? String == "10000" {
//            typeName = "回收"
//        }
//        self.showLoadHUD(title: "\(typeName)中..." as NSString)
//        RequestHelper.post(atPath: "/kz/gp/onekeyri",  withData: ["toid":dict["id"] as? String ?? ""], withCompletion: { data in
//            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//            print("一键\(typeName)：\(responseObject)")
//            let code = responseObject["c"] as! Int
//            DispatchQueue.main.async {
//                self.dismissLoadHUD()
//            }
//            if code == 0 {
//                DispatchQueue.main.async {
//                 //   self.requestEagleeyes()
//                    for(index,value) in (self.arrayList?.enumerated())!{
//                        let gpid = value["id"] as? String
//                        if gpid != nil && gpid != ""{
//                            var dict = value
//                       //     dict = self.arrayList![indexPath.row]
//                                if value["status"] != nil{
//                                    dict.removeValue(forKey: "status")
//                                    dict["val"] = "读取中..."
//                                    self.arrayList![index] = dict
//                                    self.tableView.reloadData()
//                                }
//                            self.getGPSBalance(gpid: gpid!, row: index)
//                        }
//                    }
//                    UIHelper.alertSimpleMessage(about: "\(typeName)成功!", withDescription: "", in: self)
//                }
//            }else if code == 999 || code == 1150 {
//                DispatchQueue.main.async {
//                    UIHelper.displayLoginExpireTip(self)
//                }
//            }else {
//                DispatchQueue.main.async {
//                    UIHelper.alertSimpleMessage(about: "发生错误: \(code) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
//                }
//            }
//        }, withError: { error in
//            print(error)
//            DispatchQueue.main.async {
//                UIHelper.alertSimpleMessage(about: "\(typeName)未成功，请稍后重试。", withDescription: "", in: self)
//                self.dismissLoadHUD()
//            }
//        })
//    }
    
    //新版接口 暂不可用
    func fundreclaim(index:Int,dict:[String:Any]){
         var typeName:String = "转帐"
        if dict["id"] as? String == "10000" {
            typeName = "回收"
        }
        self.showLoadHUD(title: "\(typeName)中..." as NSString)
        NetWorkRequest(API.fundreclaim(url: "cb271e2", gpid:dict["id"] as? String ?? "-1"), completion: { (responseData,statusCode,strData) -> (Void) in
            let dataDict =  responseData["data"].dictionaryObject
            let response = dataDict?["response"] as? [String:Any]
        //    let code = response?["c"] as? Int ?? -1
            // let data =  response?["data"] as? [String:Any] ?? [:]
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                  //   self.requestEagleeyes()
                    for(index,value) in (self.arrayList?.enumerated())!{
                        let gpid = value["id"] as? String
                        if gpid != nil && gpid != ""{
                            self.getGPSBalance(gpid: gpid!, row: index)
                        }
                    }
                    UIHelper.alertSimpleMessage(about: "\(typeName)成功!", withDescription: "", in: self)
//                }else if code == 999 || code == 1150 {
//                    DispatchQueue.main.async {
//                        UIHelper.displayLoginExpireTip(self)
//                    }
//                }else {
//                    DispatchQueue.main.async {
//                        UIHelper.alertSimpleMessage(about: "发生错误: \(code) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
//                    }
//                }
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "转帐未成功，请稍后重试。", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
            }
        }
    }
   
    //先回收所有金额至主账户
    func transferAccounts(index:Int,dict:[String:Any]){
        if arrayList != nil {
           self.isNoLogin = false
           var typeName:String = "转入"
           if dict["id"] as? String ?? "" == "10000" {
                typeName = "回收"
            }
            var outIdStr = ""
            var moneySum = 0.0
            let ingpid = dict["id"] as? String ?? ""
            var isHave = false
            //循环获取有余额的游戏平台id
             for (index, item1) in arrayList!.enumerated(){
                 let money = item1["val"] as? String ?? "0.00"
                 if money != "0.00" &&  money != "维护中..." && money != "读取中..." && ingpid != item1["id"] as? String ?? "" && "10000" != item1["id"] as? String ?? "" {
                    let outId  = item1["id"] as? String ?? ""
                    isHave = true
                    if outId != ""{
                       outIdStr.append(contentsOf: outId)
                        if index+1 != arrayList?.count ?? 0 {
                            outIdStr.append(contentsOf: ",")
                        }
                    }
                 }else if money != "0.00" &&  money != "维护中..." && money != "读取中..." && ingpid != item1["id"] as? String ?? "" && "10000" == item1["id"] as? String ?? ""{
                    moneySum += Double(money) ?? 0.0
                }
            }
            print("转出的id组合:\(outIdStr)")
            self.showLoadHUD(title: "\(typeName)中..." as NSString)
            if outIdStr == "" && ingpid != "10000" { //当前不是回收 并且其它平台没有金额 那么金额可能存在主账户 则需要单个刷新金额
                 self.oneKeyTransaction(InId: ingpid, moneySum:String(format: "%.2f", moneySum),outIds:"10000")
                 return
            }else if outIdStr == "" && ingpid == "10000"{ //当前是回收 并且其它平台有金额
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    UIHelper.alertSimpleMessage(about: typeName+"成功!", withDescription: "", in: self)
                }
                return
            }
            //转入到主账户
            NetWorkRequest(API.transferAccounts(url: "1d8a7a1", gpids: ""), completion: { (responseData,statusCode,strData) -> (Void) in
                let dataDict =  responseData["data"].dictionaryValue
                let response = dataDict["response"]?.dictionaryValue
                if dict["id"] as? String ?? "" == "10000" {
                   //这里就不需要再调用转入接口了 但是需要刷新
                    DispatchQueue.main.async {
                        self.dismissLoadHUD()
                        UIHelper.alertSimpleMessage(about: typeName+"成功!", withDescription: "", in: self)
                        self.refreshAcount(refreshid: "10000")
                        let outidArr = outIdStr.components(separatedBy:",")
                         for(_,outid) in outidArr.enumerated(){
                             self.refreshAcount(refreshid: outid)
                         }
                    }
                }else{
                    let d = response?["d"]?.dictionaryValue
                   let resultArray = d?["o"]?.array ?? []
                    for (_,value) in resultArray.enumerated(){
                        let dict =  value.dictionaryValue
                        let r  = dict["r"]?.dictionaryValue
                        let code = r?["c"]?.intValue
                        if code == 0{
                            let gpid = value["gpid"].stringValue
                            for (_, item1) in self.arrayList!.enumerated(){
                                let money = item1["val"] as? String ?? "0.00"
                                if gpid == item1["id"] as? String ?? "-1" && money != "0.00" &&  money != "维护中..." && money != "读取中..."{
                                    moneySum += Double(money) ?? 0.0
                                    break
                                }
                            }
                        }
                    }
                    self.oneKeyTransaction(InId: dict["id"] as? String ?? "", moneySum:String(format: "%.2f", moneySum),outIds: outIdStr)
                }
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    if reCode == "21002"{
                        UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
            }) { () -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    UIHelper.alertSimpleMessage(about: "转帐未成功，请稍后重试。", withDescription: "", in: self)
                    self._loadView?.removeFromSuperview()
                }
            }
           
           
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return  self.arrayList!.count+1
        }else if section == 2{
            return 1
        }
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == self.arrayList!.count {
                return 115
            }else{
                return 51
            }
        
        }else if indexPath.section == 2{
             return 94
        } else{
            return 51
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var headerView : MainAccountHeaderView? =  (tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifierHeadID as String) as? MainAccountHeaderView)
        if headerView == nil {
            headerView = MainAccountHeaderView(reuseIdentifier: reuseIdentifierHeadID as String)
        }
        if section == 0 {
            headerView?.setData(isList: true)
        }else{
            headerView?.setData(isList: false)
        }
        return  headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2{
            return 0
        }
            
        return 39.5
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == self.arrayList!.count { //一键回收
                var cell :MainAccountBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? MainAccountBtnCell
                if cell == nil {
                    cell =  MainAccountBtnCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
                }
                cell?.callInClickBlock({() in
                    ToolHelper.statisticsPage(pageName: "我的-主账户-一键回收")
                    self.transferAccounts(index: 0, dict: ["id":"10000"])
                })
                cell?.setData(index: self.arrayList!.count)
                return cell!
                
            }else{ //一键转入游戏列表
                var cell :MainAccountCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? MainAccountCell
                if cell == nil {
                    cell =  MainAccountCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
                }
                cell?.callClickBlock({ (index) in
                    let dict:[String:Any] =  self.arrayList![index]
                    let name:String = dict["name"] as! String
                      ToolHelper.statisticsPage(pageName: "我的-主账户-\(name)一键转入")
                    if dict["status"] == nil { //读取中..
                          UIHelper.alertSimpleMessage(about: "平台读取中...", withDescription: "", withOKButton: false)
                    }else if dict["status"] as! Int == 1 { //读取成功
                         self.transferAccounts(index: index, dict: dict)
                    }else if dict["status"] as! Int  == 2 { //读取失败!
                         UIHelper.alertSimpleMessage(about: "无法转帐，请重新获取!", withDescription: "", withOKButton: false)
                       //  self.outOrIn(index: index, dict: dict)
                    }else if dict["status"] as! Int  == 0 { //维护中...
                        UIHelper.alertSimpleMessage(about: "平台维护中...", withDescription: "", withOKButton: false)
                    }else{
                         self.transferAccounts(index: index, dict: dict)
                    }
                    
                })
                cell?.setData(dict: self.arrayList?[indexPath.row],index:indexPath.row)
                return cell!
            }
        }else if indexPath.section == 2{ //提交按钮
            var cell :MainAccountSubmitBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID5 as String) as? MainAccountSubmitBtnCell
            if cell == nil {
                cell =  MainAccountSubmitBtnCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID5 as String)
            }
            cell?.callClickBlock({ //提交转账
                ToolHelper.statisticsPage(pageName: "我的-主账户-提交")
                self.actionToTransfer()
            })
            return cell!
        }else{
            if indexPath.row == 0 || indexPath.row == 1 { //转账item
                var cell :MainAccountSelectCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? MainAccountSelectCell
                if cell == nil {
                    cell =  MainAccountSelectCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
                }
                if indexPath.row == 0{
                    cell?.setData(iconName: "icon_mainAccount_out", title: "转出", dict:self.outDict)
                    
                }else if indexPath.row == 1{
                    cell?.setData(iconName: "icon_mainAccount_in", title: "转入", dict:self.inDict)
                }
                 return cell!
            }else{
                var cell :MainAccountInputCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID4 as String) as? MainAccountInputCell
                if cell == nil {
                    cell =  MainAccountInputCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID4 as String)
                }
                cell?.callChangeBlock({ (money) in
                    DispatchQueue.main.async {
                       self.moneyStr = money
                    }
                })
                
                cell?.setData(money: self.moneyStr)
                return cell!
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == self.arrayList!.count { //一键回收
            
            }else{
                var dict = self.arrayList![indexPath.row]
                    let gpid = dict["id"] as? String
                    if gpid != nil && gpid != ""{
                        if dict["status"] == nil{
                             UIHelper.alertSimpleMessage(about: "读取中,请稍后...", withDescription: "", withOKButton: false)
                        }else{
                           dict.removeValue(forKey: "status")
                           dict["val"] = "读取中..."
                           self.arrayList![indexPath.row] = dict
                           self.tableView.reloadData()
                           self.getGPSBalance(gpid: gpid!, row: indexPath.row)
                        }
                    }
            }
        }else if indexPath.section == 1{ //转账
            if indexPath.row == 0{  //转出
                  ToolHelper.statisticsPage(pageName: "我的-主账户-转出")
                let popView =  MainAccountPopView.init(list: self.arrayList!)
                popView.type = 1
                popView.selectDict = self.outDict
                popView.callClickBlock { (row) in
                    DispatchQueue.main.async {
                        self.outDict = self.arrayList![row]
                        self.tableView.reloadData()
                    }
                }
                popView.show(target: self, animated: true)
            }else if indexPath.row == 1{ //转入
                let popView =  MainAccountPopView.init(list: self.arrayList!)
                 popView.type = 2
                 popView.selectDict = self.inDict
                popView.callClickBlock { (row) in
                    DispatchQueue.main.async {
                        self.inDict = self.arrayList![row]
                        self.tableView.reloadData()
                    }
                }
                 ToolHelper.statisticsPage(pageName: "我的-主账户-转入")
                popView.show(target: self, animated: true)
            }
        }
    }
    //一键转入
    func oneKeyTransaction(InId : String,moneySum:String,outIds:String) -> Void{
        NetWorkRequest(API.transaction(url: "0ef07eb", tout: "10000", tin: InId,amount: moneySum), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                    self.dismissLoadHUD()
                let dataDict =  responseData["data"].dictionaryObject
                let response = dataDict?["response"] as? [String:Any]
                let code = response?["c"] as? Int ?? -1
                if code == 0{
                   UIHelper.alertSimpleMessage(about: "转入成功!", withDescription: "", in: self)
                }else{
                   UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
            if outIds == "10000" { //只需要刷新主账户余额 和转入id的余额
                    self.refreshAcount(refreshid: "10000")
                    self.refreshAcount(refreshid: InId)
                }else{ //需要刷新 10000和转出ids的余额和转入id的余额
                    self.refreshAcount(refreshid: "10000")
                    self.refreshAcount(refreshid: InId)
                   let outidArr = outIds.components(separatedBy:",")
                    for(_,outid) in outidArr.enumerated(){
                        self.refreshAcount(refreshid: outid)
                    }
                }

             self.tableView.reloadData()
                    
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "转帐未成功，请稍后重试。", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
            }
        }
    }
    
    func refreshAcount(refreshid:String){
        for(index,value) in (self.arrayList?.enumerated())!{
            let gpid = value["id"] as? String
            if gpid != nil && gpid != ""{
                if gpid == refreshid{
                    var dict = value
                    if value["status"] != nil{
                        dict.removeValue(forKey: "status")
                        dict["val"] = "读取中..."
                        self.arrayList![index] = dict
                        self.tableView.reloadData()
                    }
                    self.getGPSBalance(gpid: gpid!, row: index)
                    break
                }
            }
        }
    }
    func actionToTransfer() -> Void {
        if UserHelper.getLoginStatus() {
            if self.outDict == nil{
                UIHelper.alertSimpleMessage(about: "请选择转出平台!", withDescription: "", in: self)
                return
            }
            if self.inDict == nil{
                UIHelper.alertSimpleMessage(about: "请选择转入平台!", withDescription: "", in: self)
                return
            }
            
            if self.moneyStr == nil{
                UIHelper.alertSimpleMessage(about: "请输入转帐金额!", withDescription: "", in: self)
                return
            }
            if self.outDict!["id"] as! String == self.inDict!["id"] as! String{
                UIHelper.alertSimpleMessage(about: "转出平台和转入平台相同!", withDescription: "", in: self)
                return
            }
         //   let outDouble : Double = Double(self.moneyStr!) ?? 0.0
            self.showLoadHUD(title: "转帐中..." as NSString)
            NetWorkRequest(API.transaction(url: "0ef07eb", tout: self.outDict?["id"] as? String ?? "", tin: self.inDict?["id"] as? String ?? "", amount: self.moneyStr!), completion: { (responseData,statusCode,strData) -> (Void) in
                let dataDict =  responseData["data"].dictionaryObject
                let response = dataDict?["response"] as? [String:Any]
                let code = response?["c"] as? Int ?? -1
               // let data =  response?["data"] as? [String:Any] ?? [:]
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    if code == 0{
                      //   self.requestEagleeyes()
                        UIHelper.alertSimpleMessage(about: "转帐成功!", withDescription: "", in: self)
                        for(index,value) in (self.arrayList?.enumerated())!{
                            let gpid = value["id"] as? String
                            if gpid != nil && gpid != ""{
                                if gpid == self.outDict!["id"] as? String ||  gpid == self.inDict!["id"] as? String{
                                    var dict = value
                                    if value["status"] != nil{
                                        dict.removeValue(forKey: "status")
                                        dict["val"] = "读取中..."
                                        self.arrayList![index] = dict
                                        self.tableView.reloadData()
                                    }
                                    self.getGPSBalance(gpid: gpid!, row: index)
                                }
                            }
                        }
                        self.moneyStr = nil
                        self.tableView.reloadData()
                    }else{
                        DispatchQueue.main.async {
                            UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                        }
                    }
                }
               
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    if reCode == "21002"{
                        UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
            }) { () -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    UIHelper.alertSimpleMessage(about: "转帐未成功，请稍后重试。", withDescription: "", in: self)
                    self._loadView?.removeFromSuperview()
                }
            }
           
        }else{
            LoginViewController.loginIfNeedController(currentController: self) {}
        }
    }
}
